package com.mass.core.generator;

import com.google.common.base.CaseFormat;
import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 
 * @ProjectName:  [demo-ht] 
 * @Package:      [generator.GeneratorTest.java]  
 * @ClassName:    [GeneratorTest]   
 * @Description:  [反向生成工具类]   
 * @Author:       [张双喜]   
 * @CreateDate:   [2018年5月27日 下午3:04:41]   
 * @UpdateUser:   [zsx]   
 * @UpdateDate:   [2018年5月27日 下午3:04:41]   
 * @Since         [JDK1.7]
 * @Version:      [v1.0]
 *
 */
public class CodeGenerator {
	

	private static String BASE_PACKAGE = "";//项目基础包名称，根据自己公司的项目修改
    private static String MODEL_PACKAGE = ".model";//Model所在包
    private static String MAPPER_PACKAGE = ".dao";//Mapper所在包
    private static String SERVICE_PACKAGE = ".service";//Service所在包
    private static String SERVICE_IMPL_PACKAGE = ".impl";//ServiceImpl所在包
    private static String CONTROLLER_PACKAGE = ".controller";//Controller所在包
    private static String INPUT_PACKAGE = ".input";//input 所在包
	private static String MAPPER_INTERFACE_REFERENCE = ".core.Mapper";//Mapper插件基础接口的完全限定名
    //JDBC配置，请修改为你项目的实际配置
	private static String JDBC_URL = "";
    private static String JDBC_USERNAME = "";
    private static String JDBC_PASSWORD = "";
    private static String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
    private static String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径
    private static String TEMPLATE_FILE_PATH = PROJECT_PATH + "/src/main/resources/template/generator";//模板位置
    private static String JAVA_PATH = "/src/main/java"; //java文件路径
    private static String RESOURCES_PATH = "/src/main/resources";//资源文件路径

    private static String AUTHOR = "zsx";//@author
    private static String DATE = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//@date

    
    public static void start() throws Exception {
    	try {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream is = classloader.getResourceAsStream("generatorConfig.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(is);
            Context context = config.getContexts().get(0);

            //获取JDBC配置
        	JDBCConnectionConfiguration jdbcConnectionConfiguration = context.getJdbcConnectionConfiguration();
        	JDBC_URL = jdbcConnectionConfiguration.getConnectionURL();
        	JDBC_USERNAME = jdbcConnectionConfiguration.getUserId();
        	JDBC_PASSWORD = jdbcConnectionConfiguration.getPassword();
            //获取实体类配置
            JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = context.getJavaModelGeneratorConfiguration();
            //实体类位置
            String targetPackage = javaModelGeneratorConfiguration.getTargetPackage();
            targetPackage = targetPackage.substring(0, targetPackage.lastIndexOf(".")); 
            BASE_PACKAGE = targetPackage;//项目基础包名称，根据自己公司的项目修改
            //javaModelGenerator
            //表格配置
            TableConfiguration tableConfiguration = context.getTableConfigurations().get(0);
        	String tableName = tableConfiguration.getTableName();
        	//生成 server,components
        	genCode(tableName);
        	tableConfiguration.setDomainObjectName(tableNameConvertUpperCamel(tableName));  //设置实体类名称
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    /**
     * 通过数据表名称生成代码，Model 名称通过解析数据表名称获得，下划线转大驼峰的形式。
     * 如输入表名称 "t_user_detail" 将生成 TUserDetail、TUserDetailMapper、TUserDetailService ...
     * @param tableNames 数据表名称...
     */
    private static void genCode(String... tableNames) {
        for (String tableName : tableNames) {
            String modelName=tableNameConvertUpperCamel(tableName);
            genCodeByCustomModelName(tableName, modelName);
        }
    }

    /**
     * 通过数据表名称，和自定义的 Model 名称生成代码
     * 如输入表名称 "t_user_detail" 和自定义的 Model 名称 "User" 将生成 User、UserMapper、UserService ...
     * @param tableName 数据表名称
     * @param modelName 自定义的 Model 名称
     */
    private static void genCodeByCustomModelName(String tableName, String modelName) {
        //genModelAndMapper(tableName, modelName);
        genService(tableName, modelName);
        genController(tableName, modelName);
        //genInput(tableName,modelName);
        //genModelAndMapper();
    }

    /**
     * 自动生成model和mapper
     * @param tableName
     * @param modelName
     */
    @SuppressWarnings("unused")
	private static void genModelAndMapper(String tableName, String modelName) {
        Context context = new Context(ModelType.FLAT);
        context.setId("Potato");
        context.setTargetRuntime("MyBatis3Simple");
        context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
        context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");

        JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
        jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
        jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
        jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
        jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
        context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);

        PluginConfiguration pluginConfiguration = new PluginConfiguration();
        pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
        pluginConfiguration.addProperty("mappers", BASE_PACKAGE + MAPPER_INTERFACE_REFERENCE);
        pluginConfiguration.setConfigurationType("");
        context.addPluginConfiguration(pluginConfiguration);

        JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
        javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
        javaModelGeneratorConfiguration.setTargetPackage(BASE_PACKAGE + MODEL_PACKAGE);
        context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);

        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
        sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH);
        sqlMapGeneratorConfiguration.setTargetPackage("mapper");
        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
        javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
        javaClientGeneratorConfiguration.setTargetPackage(BASE_PACKAGE + MAPPER_PACKAGE);
        javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

        TableConfiguration tableConfiguration = new TableConfiguration(context);
        tableConfiguration.setTableName(tableName);
        if (StringUtils.isNotEmpty(modelName)){
            tableConfiguration.setDomainObjectName(modelName);
        }
        tableConfiguration.setGeneratedKey(new GeneratedKey("id", "Mysql", true, null));
        tableConfiguration.setCountByExampleStatementEnabled(true);//通过example 计数
        tableConfiguration.setUpdateByExampleStatementEnabled(true);//通过example 修改
        tableConfiguration.setDeleteByExampleStatementEnabled(true);//通过example 删除
        tableConfiguration.setSelectByExampleStatementEnabled(true);//通过example 查找
        context.addTableConfiguration(tableConfiguration);

        List<String> warnings;
        MyBatisGenerator generator;
        try {
            Configuration config = new Configuration();
            config.addContext(context);
            config.validate();

            boolean overwrite = true;
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            warnings = new ArrayList<String>();
            generator = new MyBatisGenerator(config, callback, warnings);
            generator.generate(null);
        } catch (Exception e) {
            throw new RuntimeException("生成Model和Mapper失败", e);
        }

        if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
            throw new RuntimeException("生成Model和Mapper失败：" + warnings);
        }
        if (StringUtils.isEmpty(modelName)) modelName = tableNameConvertUpperCamel(tableName);
        System.out.println(modelName + ".java 生成成功");
        System.out.println(modelName + "Mapper.java 生成成功");
        System.out.println(modelName + "Mapper.xml 生成成功");
    }

    /**
     * 自动生成service
     * @param tableName
     * @param modelName
     */
    private static void genService(String tableName, String modelName) {
        try {
        	
            String PACKAGE_PATH_SERVICE = packageConvertPath(BASE_PACKAGE + SERVICE_PACKAGE);//生成的Service存放路径
            String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(BASE_PACKAGE + SERVICE_PACKAGE + SERVICE_IMPL_PACKAGE);//生成的Service实现存放路径
        	
            freemarker.template.Configuration cfg = getConfiguration();

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("date", DATE);
            data.put("author", AUTHOR);
            String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
            data.put("modelNameUpperCamel", modelNameUpperCamel);
            data.put("modelNameLowerCamel", tableNameConvertLowerCamel(tableName));
            data.put("basePackage", BASE_PACKAGE);

            File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE + modelNameUpperCamel + "Service.java");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            cfg.getTemplate("p-service.ftl").process(data,
                    new FileWriter(file));
            System.out.println(modelNameUpperCamel + "Service.java 生成成功");

            File file1 = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE_IMPL + modelNameUpperCamel + "ServiceImpl.java");
            if (!file1.getParentFile().exists()) {
                file1.getParentFile().mkdirs();
            }
            cfg.getTemplate("p-service-impl.ftl").process(data,
                    new FileWriter(file1));
            System.out.println(modelNameUpperCamel + "ServiceImpl.java 生成成功");
        } catch (Exception e) {
        	e.printStackTrace();
            throw new RuntimeException("生成Service失败", e);
        }
    }

    /**
     * 自动生成controller
     * @param tableName
     * @param modelName
     */
    private static void genController(String tableName, String modelName) {
        try {
        	String PACKAGE_PATH_CONTROLLER = packageConvertPath(BASE_PACKAGE + CONTROLLER_PACKAGE);//生成的Controller存放路径
            freemarker.template.Configuration cfg = getConfiguration();

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("date", DATE);
            data.put("author", AUTHOR);
            String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
            data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
            data.put("modelNameUpperCamel", modelNameUpperCamel);
            data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
            data.put("basePackage", BASE_PACKAGE);

            File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //cfg.getTemplate("components-restful.ftl").process(data, new FileWriter(file));
            cfg.getTemplate("p-controller.ftl").process(data, new FileWriter(file));

            System.out.println(modelNameUpperCamel + "Controller.java 生成成功");
        } catch (Exception e) {
            throw new RuntimeException("生成Controller失败", e);
        }

    }

    /**
     * 自动生成input对象
     * @param tableName
     * @param modelName
     */
    @SuppressWarnings("unused")
	private static void genInput(String tableName, String modelName) {
        try {
        	String PACKAGE_PATH_INPUT = packageConvertPath(BASE_PACKAGE + INPUT_PACKAGE);//生成的Input存放路径
            
            freemarker.template.Configuration cfg = getConfiguration();

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("date", DATE);
            data.put("author", AUTHOR);
            String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
            //data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
            data.put("modelNameUpperCamel", modelNameUpperCamel);
            //data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
            data.put("basePackage", BASE_PACKAGE);

            File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_INPUT + modelNameUpperCamel + "Input.java");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //cfg.getTemplate("components-restful.ftl").process(data, new FileWriter(file));
            cfg.getTemplate("input.ftl").process(data, new FileWriter(file));

            System.out.println(modelNameUpperCamel + "Input.java 生成成功");
        } catch (Exception e) {
            throw new RuntimeException("生成Input失败", e);
        }

    }

    private static freemarker.template.Configuration getConfiguration() throws IOException {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        return cfg;
    }

    private static String tableNameConvertLowerCamel(String tableName) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, tableName.toLowerCase());
    }

    private static String tableNameConvertUpperCamel(String tableName) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());

    }

    private static String tableNameConvertMappingPath(String tableName) {
        tableName = tableName.toLowerCase();//兼容使用大写的表名
        return "/" + (tableName.contains("_") ? tableName.replaceAll("_", "/") : tableName);
        //return "/"+tableName;
    }

    private static String modelNameConvertMappingPath(String modelName) {
        String tableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, modelName);
        return tableNameConvertMappingPath(tableName);
    }

    private static String packageConvertPath(String packageName) {
        return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
    }
}